package top.hg.tool.modules.car.article;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import top.hg.tool.modules.car.constant.RedisKeyConstant;

import java.util.List;

/**
 * @Author: skh
 * @Date: 2019/7/24 16:53
 * @Description:
 */
@Repository
@Slf4j
public class ArticleRepository {

    @Autowired
    private ArticleDao articleDao;

    @Cacheable(cacheNames = RedisKeyConstant.car_article_detail, key = "#id")
    public ArticleEntity getArticleById(Integer id) {
        log.info("get article from db, id:[{}]", id);
        ArticleEntity articleEntity = articleDao.selectById(id);
        return articleEntity;
    }

    @Cacheable(cacheNames = RedisKeyConstant.car_article_list)
    public List<ArticleEntity> getArticleList() {
        log.info("get articleList from db");
        EntityWrapper<ArticleEntity> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id", "title", "author", "create_time", "read_count");
        wrapper.orderBy("create_time", false);
        List<ArticleEntity> articleEntityList = articleDao.selectList(wrapper);
        return articleEntityList;
    }

    @CacheEvict(cacheNames = RedisKeyConstant.car_article_list, allEntries = true)
    public Integer saveArticle(ArticleEntity articleEntity) {
        articleDao.insert(articleEntity);
        log.info("新增文章成功,文章id:[{}]",articleEntity.getId());
        return articleEntity.getId();
    }

    public void updateArticleById(ArticleEntity articleEntity) {
        articleDao.updateById(articleEntity);
    }
}
